package com.sunzm.common.utils.mysql;

import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariDataSource;
import org.apache.commons.dbutils.DbUtils;

import java.sql.*;

/**
 * HikariCP连接池测试
 *
 * @author sunzm
 * @version 1.0
 * @date 2022-01-29
 */
public class HikariCPDemo {
    public static void main(String[] args) {
        Connection connection = null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;
        HikariDataSource ds = null;
        try {
            HikariConfig config = new HikariConfig("/hikari.properties");
            config.addDataSourceProperty("cachePrepStmts", "true");
            config.addDataSourceProperty("prepStmtCacheSize", "250");
            config.addDataSourceProperty("prepStmtCacheSqlLimit", "2048");
            ds = new HikariDataSource(config);

            connection = ds.getConnection();

            String sqlStr = "SELECT * FROM open_msg_config";

            pstmt = connection.prepareStatement(sqlStr);

            rs = pstmt.executeQuery();

            while (rs.next()) {
                ResultSetMetaData metaData = rs.getMetaData();

                int columnCount = metaData.getColumnCount();

                StringBuilder printBulder = new StringBuilder();
                for (int i = 1; i < columnCount + 1; i++) {
                    printBulder.append(metaData.getColumnName(i) + " -> " + rs.getString(i))
                            .append(System.lineSeparator());
                }
                System.out.println(printBulder);
                System.out.println("==============================");
            }

            ds.close();
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            DbUtils.closeQuietly(connection, pstmt, rs);

            try {
                if (ds != null) {
                    ds.close();
                }
            } catch (Exception ex) {}
        }
    }
}
